import { onBeforeUnmount } from 'vue'

/**
 * 监听页面可见性
 */
export function useVisibilityChangeListener(onVisible: Function, onHidden: Function) {
    const callback = () => {
        const state = document.visibilityState
        if (state === 'visible') {
            onVisible()
        }
        if (state === 'hidden') {
            onHidden()
        }
    }
    useDomEventListener('visibilitychange', callback)
}

/**
 * 监听DOM事件
 */
export function useDomEventListener<K extends keyof DocumentEventMap>(type: K, callback: (ev: DocumentEventMap[K]) => any) {
    document.addEventListener(type, callback)
    onBeforeUnmount(() => document.removeEventListener(type, callback))
}
